package com.jinzhi.jzweb.controller;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.jinzhi.common.annotation.Log;
import com.jinzhi.common.base.BaseController;
import com.jinzhi.common.service.DictService;
import com.jinzhi.common.utils.DateUtil;
import com.jinzhi.common.utils.Result;
import com.jinzhi.jzweb.domain.*;
import com.jinzhi.jzweb.service.*;
import com.jinzhi.jzweb.utils.IdCardUtil;
import com.jinzhi.sys.domain.UserDO;
import com.jinzhi.sys.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * <pre>
 * 考点人员安排
 * </pre>
 * <small> 2020-02-24 21:00:11 | lance</small>
 */
@Controller
@RequestMapping("/jzweb/personnelArrangement")
public class PersonnelArrangementController extends BaseController {
    @Autowired
    private PersonnelArrangementService personnelArrangementService;
    @Autowired
    private UserService userService;
    @Autowired
    private OrganizationNewsService organizationNewsService;
    @Autowired
    private ExaminationBatchService examinationBatchService;
    @Autowired
    private ExpertsService expertsService;
    @Autowired
    private ExaminationPointService examinationPointService;
    @Autowired
    private OrganizationRolesService organizationRolesService;
    @Autowired
    private CertificationBatchService certificationBatchService;
    @Autowired
    private StuSignUpService stuSignUpService;
    @Autowired
    private DictService dictService;
    @Autowired
    private ExaminationRoomService examinationRoomService;

    @GetMapping()
    @RequiresPermissions("jzweb:personnelArrangement:personnelArrangement")
    String PersonnelArrangement() {
        return "jzweb/personnelArrangement/personnelArrangement";
    }

    @ResponseBody
    @GetMapping("/list")
    @RequiresPermissions("jzweb:personnelArrangement:personnelArrangement")
    public Result<Page<PersonnelArrangementDO>> list(HttpServletRequest req, PersonnelArrangementDO personnelArrangementDTO) {
        Wrapper<PersonnelArrangementDO> wrapper = new EntityWrapper<PersonnelArrangementDO>().orderBy("id", false);
        if (personnelArrangementDTO.getCbatchId() != null){
            wrapper.eq("cbatch_id",personnelArrangementDTO.getCbatchId());
        }
        if (personnelArrangementDTO.getState() != null){
            wrapper.eq("state",personnelArrangementDTO.getState());
        }
        if (StringUtils.isNotBlank(personnelArrangementDTO.getUserName())){
            Wrapper<UserDO> userWrapper = new EntityWrapper<UserDO>().like("name",personnelArrangementDTO.getUserName());
            List<UserDO>  userDOS = userService.selectList(userWrapper);
            String str = "";
            for (UserDO userDO : userDOS){
                str = str + userDO.getId() + ",";
            }
            wrapper.and();
            if(StringUtils.isNotBlank(str)){
                wrapper.in("user_id",str.substring(0,str.length()-1));
            }else{
                wrapper.eq("user_id",null);
            }
        }

        String roleName = getRoleNames();//查询用户角色
        if (!roleName.contains("超级用户角色")) {
            Object orgId = req.getSession().getAttribute("orgId");
            if (orgId != null) {
                wrapper.eq("org_id",orgId);
            } else {
                wrapper.eq("org_id",this.getUser().getOrgId());
            }
        }else {
            if (StringUtils.isNotBlank(personnelArrangementDTO.getOrgName())){
                Wrapper<OrganizationNewsDO> orWrapper = new EntityWrapper<OrganizationNewsDO>().like("name",personnelArrangementDTO.getOrgName());
                List<OrganizationNewsDO>  organizationNewsDOS = organizationNewsService.selectList(orWrapper);
                String str = "";
                for (OrganizationNewsDO organizationNewsDO : organizationNewsDOS){
                    str = str + organizationNewsDO.getId() + ",";
                }
                wrapper.and();
                if(StringUtils.isNotBlank(str)){
                    wrapper.in("org_id",str.substring(0,str.length()-1));
                }else{
                    wrapper.eq("org_id",null);
                }
            }
        }

        Page<PersonnelArrangementDO> page = personnelArrangementService.selectPage(getPage(PersonnelArrangementDO.class), wrapper);
        List list = new ArrayList();
        for (int i = 0; i < page.getRecords().size(); i++) {
            PersonnelArrangementDO obj = (PersonnelArrangementDO) page.getRecords().get(i);
            if (obj.getCreaterId() != null) {
                UserDO user = userService.selectById(obj.getCreaterId());
                if (user != null) {
                    obj.setCreaterName(user.getUsername());
                }
            }

            if (obj.getUserId() != null) {
                UserDO user1 = userService.selectById(obj.getUserId());
                if (user1 != null) {
                    obj.setUserName(user1.getName());
                    obj.setUserArea(user1.getProvince());
                    obj.setUserPhone(user1.getMobile());
                    if (user1.getOrgId() != null) {
                        OrganizationNewsDO organizationNewsDO = organizationNewsService.selectById(user1.getOrgId());
                        if (organizationNewsDO != null) {
                            obj.setUserOrgName(organizationNewsDO.getName());
                        }
                    }
                }
            }

            if (obj.getOrgId() != null) {
                OrganizationNewsDO organizationNewsDO = organizationNewsService.selectById(obj.getOrgId());
                if (organizationNewsDO != null) {
                    obj.setOrgName(organizationNewsDO.getName());
                    obj.setOrgArea(organizationNewsDO.getProvince());
                }
            }

            if (obj.getCbatchId() != null) {
                CertificationBatchDO certificationBatchDO = certificationBatchService.selectById(obj.getCbatchId());
                if (certificationBatchDO != null) {
                    obj.setCbatchName(certificationBatchDO.getName());
                }
            }
            list.add(obj);
        }
        page.setRecords(list);
        return Result.ok(page);
    }

    @GetMapping("/add")
    @RequiresPermissions("jzweb:personnelArrangement:add")
    String add(Model model) {
        return "jzweb/personnelArrangement/add";
    }

    @GetMapping("/edit/{id}")
    @RequiresPermissions("jzweb:personnelArrangement:edit")
    String edit(@PathVariable("id") Long id, Model model) {
        PersonnelArrangementDO personnelArrangement = personnelArrangementService.selectById(id);
        if (personnelArrangement.getOrgId() != null) {
            OrganizationNewsDO organizationNewsDO = organizationNewsService.selectById(personnelArrangement.getOrgId());
            if (organizationNewsDO != null) {
                personnelArrangement.setProvince(organizationNewsDO.getProvince());
            } else {
                personnelArrangement.setProvince("");
            }
        } else {
            personnelArrangement.setProvince("");
        }
        if (personnelArrangement.getContents() != null) {
            if (personnelArrangement.getContents().equals("考评员")) {
                personnelArrangement.setExpType("0");
            } else if (personnelArrangement.getContents().equals("督导员")) {
                personnelArrangement.setExpType("3");
            } else {
                personnelArrangement.setContents("");
            }
        } else {
            personnelArrangement.setContents("");
        }
        if (personnelArrangement.getUserId() != null) {
            UserDO userDO = userService.selectById(personnelArrangement.getUserId());
            model.addAttribute("userNames", userDO.getName());
        } else {
            model.addAttribute("userNames", "");
        }
        model.addAttribute("personnelArrangement", personnelArrangement);
        return "jzweb/personnelArrangement/edit";
    }

    @Log("添加考点人员安排")
    @ResponseBody
    @PostMapping("/save")
    @RequiresPermissions("jzweb:personnelArrangement:add")
    public Result<String> save(PersonnelArrangementDO personnelArrangement) {
        if (personnelArrangement.getExpType() != null) {
            if (personnelArrangement.getExpType().equals("3")) {
                personnelArrangement.setContents("督导员");
            } else if (personnelArrangement.getExpType().equals("0")) {
                personnelArrangement.setContents("考评员");
            }
        }

        personnelArrangement.setCreaterId(this.getUserId());
        personnelArrangementService.insert(personnelArrangement);
        return Result.ok();
    }

    @Log("修改考点人员安排")
    @ResponseBody
    @RequestMapping("/update")
    @RequiresPermissions("jzweb:personnelArrangement:edit")
    public Result<String> update(PersonnelArrangementDO personnelArrangement) {
        if (personnelArrangement.getExpType() != null) {
            if (personnelArrangement.getExpType().equals("3")) {
                personnelArrangement.setContents("督导员");
            } else if (personnelArrangement.getExpType().equals("0")) {
                personnelArrangement.setContents("考评员");
            }
        }

        boolean update = personnelArrangementService.updateById(personnelArrangement);
        return update ? Result.ok() : Result.fail();
    }

    @Log("确认考点人员信息")
    @PostMapping("/confirms")
    @ResponseBody
    @RequiresPermissions("jzweb:personnelArrangement:remove")
    public Result<String> confirms(Long id) {
        PersonnelArrangementDO personnelArrangementDO = personnelArrangementService.selectById(id);
        personnelArrangementDO.setState(1);//将状态修改为已确认
        return personnelArrangementService.updateById(personnelArrangementDO) ? Result.ok() : Result.fail("确认失败，请重试！");
    }

    @Log("批量确认考点人员信息")
    @PostMapping("/batchConfirms")
    @ResponseBody
    @RequiresPermissions("jzweb:personnelArrangement:batchRemove")
    public Result<String> batchConfirms(@RequestParam("ids[]") Long[] ids) {
        List<PersonnelArrangementDO> personnelArrangementDOS = new ArrayList<>();
        if (ids != null && ids.length > 0) {
            for (int i = 0; i < ids.length; i++) {
                PersonnelArrangementDO personnelArrangementDO = personnelArrangementService.selectById(ids[i]);
                personnelArrangementDO.setState(1);//将状态修改为已确认
                personnelArrangementDOS.add(personnelArrangementDO);
            }
        }
        if (personnelArrangementDOS.size() > 0) {
            return personnelArrangementService.updateBatchById(personnelArrangementDOS, personnelArrangementDOS.size()) ? Result.ok() : Result.fail("确认失败，请重试！");
        }

        return Result.ok();
    }

    @Log("删除考点人员安排")
    @PostMapping("/remove")
    @ResponseBody
    @RequiresPermissions("jzweb:personnelArrangement:remove")
    public Result<String> remove(Long id) {
        personnelArrangementService.deleteById(id);
        return Result.ok();
    }

    @Log("批量删除考点人员安排")
    @PostMapping("/batchRemove")
    @ResponseBody
    @RequiresPermissions("jzweb:personnelArrangement:batchRemove")
    public Result<String> remove(@RequestParam("ids[]") Long[] ids) {
        personnelArrangementService.deleteBatchIds(Arrays.asList(ids));
        return Result.ok();
    }

    @Log("查询考点")
    @GetMapping("/selProTestCenter")
    @ResponseBody
    public Result<?> selProTestCenter(String province) {
        if (StringUtils.isNotBlank(province)) {
            Map map = new HashMap();
            map.put("roleType", 5);
            map.put("province", province);
            List<Map> maps = organizationRolesService.selByRoleProvince(map);
            return Result.ok(maps);
        } else {
            return Result.fail("请先选择省份！");
        }
    }

    @Log("查询专家")
    @GetMapping("/selectExpert")
    @ResponseBody
    public Result<?> selectExpert(String cbatchId, String province, String orgId, String type, String status,String orgType) {
        List<Map> maps;
        Map map = new HashMap();
        map.put("orgId", orgId);
        map.put("type", type);
        map.put("province", province);
        if (StringUtils.isNotBlank(cbatchId)) {
            List<Long> userIdLists = personnelArrangementService.selUserIdLists(Long.parseLong(cbatchId));
            if (userIdLists != null && userIdLists.size() > 0) {
                map.put("userIds", userIdLists);
            }
        }

        //orgType:0校内考评员、1校外考评员
        if(orgType.equals(1)){
            //status0省内安排，1省外安排
            if (status.equals("0")) {
                maps = expertsService.selByTypeProvince(map);
            } else {
                maps = expertsService.selByTypeNoProvince(map);
            }
        }else{
            maps = expertsService.selByOrgType(map);
        }

        return Result.ok(maps);
    }

    @Log("查询认证批次")
    @GetMapping("/selAllCbatch")
    @ResponseBody
    public Result<?> selAllCbatch() {
        List<Map> allCbatch = personnelArrangementService.selAllCbatch();
        return Result.ok(allCbatch);
    }

    @Log("安排考点人员及调配查询所有认证批次并倒序排列")
    @GetMapping("/selCbatchSelect")
    @ResponseBody
    public Result<?> selCbatchSelect() {
        List<Map<Object, Object>> allCbatch = certificationBatchService.selByNameId();
        return Result.ok(allCbatch);
    }


    @Log("一键安排校内考点人员")
    @GetMapping("/saveOrgExperts")
    @ResponseBody
    public Result<?> saveOrgExperts(String cbatchId) {
        StringBuilder sbOne = new StringBuilder();
        StringBuilder sbTwo = new StringBuilder();
        if (StringUtils.isNotBlank(cbatchId)) {
            //先查询认证批次报名时间是否结束，且认证批次是否还存在已缴费和待分配状态的考生，如有，不能安排考点人员；
            CertificationBatchDO certificationBatchDO = certificationBatchService.selectById(Long.parseLong(cbatchId));
            if (certificationBatchDO != null) {
                //现在时间大于认证批次报名结束时间
                Date date = new Date();
                if (date.after(certificationBatchDO.getEndTime())) {
                    //判断是否存在未分配的考生
                    boolean stucc = stuSignUpService.selStuStateIfNull(Long.parseLong(cbatchId));
                    if (stucc) {
                        //根据认证批次id，查询相应的考试批次
                        ExaminationBatchDO examinationBatchDO = examinationBatchService.findOneByKv("cbatch_id", Long.parseLong(cbatchId), "type", 0);
                        if (examinationBatchDO != null) {
                            //循环利用考试批次id查询出所有考点
                            List<Long> orgIds = examinationPointService.selOrgIdLists(examinationBatchDO.getId());
                            if (orgIds != null && orgIds.size() > 0) {
                                for (Long orgID : orgIds) {
                                    //先查询每个考点已分配的专家
                                    Map mapUser = new HashMap();
                                    mapUser.put("cbatchId", Long.parseLong(cbatchId));
                                    mapUser.put("orgId", orgID);
                                    List<Long> userIdLists = personnelArrangementService.selOrgUserId(mapUser);
                                    if (userIdLists == null || userIdLists.size() < 1) {
                                        userIdLists = new ArrayList<>();
                                    }

                                    OrganizationNewsDO organizationNewsDO = organizationNewsService.selectById(orgID);
                                    //查询到考点的所有已分配的考生数
                                    List<StuSignUpDO> stuSignUpDOS = stuSignUpService.findByKv("cbatch_id", Long.parseLong(cbatchId), "org_id", orgID, "state", 3);
                                    if (stuSignUpDOS != null && stuSignUpDOS.size() > 0) {
                                        int stus = 40;

                                        Map<String, String> mapstus = new HashMap<>();
                                        mapstus.put("name", "考场人数");
                                        mapstus.put("type", "room_number_stu");
                                        String values = dictService.selDicBy(mapstus);
                                        if (org.apache.commons.lang.StringUtils.isNotBlank(values)) {
                                            //判断是否为数字
                                            if (IdCardUtil.isNumeric(values)) {
                                                stus = Integer.parseInt(values);
                                            }
                                        }

                                        int theorys;//理论考场数
                                        if ((stuSignUpDOS.size() % stus) == 0) {
                                            theorys = stuSignUpDOS.size() / stus;
                                        } else {
                                            theorys = (stuSignUpDOS.size() / stus) + 1;
                                        }

                                        int maxDurationNum = 20;
                                        int examinationRoomNum = 6;
                                        mapstus.clear();
                                        mapstus.put("name", "技能考试每组最大时长");
                                        mapstus.put("type", "max_duration");
                                        String maxDuration = dictService.selDicBy(mapstus);
                                        if (org.apache.commons.lang.StringUtils.isNotBlank(maxDuration)) {
                                            //判断是否为数字
                                            if (IdCardUtil.isNumeric(maxDuration)) {
                                                maxDurationNum = Integer.parseInt(maxDuration);
                                            }
                                        }
                                        mapstus.clear();
                                        mapstus.put("name", "技能考场工位数");
                                        mapstus.put("type", "examination_room_number");
                                        String examinationRoomNumber = dictService.selDicBy(mapstus);
                                        if (org.apache.commons.lang.StringUtils.isNotBlank(examinationRoomNumber)) {
                                            //判断是否为数字
                                            if (IdCardUtil.isNumeric(examinationRoomNumber)) {
                                                examinationRoomNum = Integer.parseInt(examinationRoomNumber);
                                            }
                                        }
                                        long minPoor = 180L;//默认为三小时
                                        ExaminationBatchDO examinationBatchDOss = examinationBatchService.findOneByKv("cbatch_id", Long.parseLong(cbatchId), "type", 1);
                                        if (examinationBatchDOss != null) {
                                            minPoor = DateUtil.getDatePoor(examinationBatchDOss.getEndTime(), examinationBatchDOss.getStartTime());//计算设置时长
                                        }

                                        //获取该机构的技能考场数量
                                        Map mapAllNum = new HashMap();
                                        mapAllNum.put("profileId", certificationBatchDO.getProfileId());
                                        mapAllNum.put("orgId", orgID);
                                        int roomAllNum = examinationRoomService.selTypeCount(mapAllNum);

                                        long stationNum;//技能考试所需考评员数
                                        if (minPoor == 0) {
                                            stationNum = 0;
                                        } else {
                                            long earooms;//技能考场数
                                            if (((stuSignUpDOS.size() * maxDurationNum) % (minPoor * examinationRoomNum)) == 0) {
                                                earooms = (stuSignUpDOS.size() * maxDurationNum) / (minPoor * examinationRoomNum);
                                            } else {
                                                earooms = (stuSignUpDOS.size() * maxDurationNum) / (minPoor * examinationRoomNum) + 1;
                                            }

                                            if(earooms > roomAllNum){
                                                if ((examinationRoomNum % 3) == 0) {
                                                    stationNum = (examinationRoomNum / 3) * roomAllNum;
                                                } else {
                                                    stationNum = ((examinationRoomNum / 3) + 1) * roomAllNum;
                                                }
                                            }else{
                                                if ((examinationRoomNum % 3) == 0) {
                                                    stationNum = (examinationRoomNum / 3) * earooms;
                                                } else {
                                                    stationNum = ((examinationRoomNum / 3) + 1) * earooms;
                                                }
                                            }
                                        }

                                        long endPerNum;//需要安排的考评员数量
                                        if (stationNum >= theorys) {
                                            endPerNum = stationNum;
                                        } else {
                                            endPerNum = theorys;
                                        }

                                        int ppes = 0;//已有考评员数
                                        //判断并增加督导员
                                        boolean iii = true;
                                        List<PersonnelArrangementDO> personnelArrangementDOs = personnelArrangementService.findByKv("cbatch_id", Long.parseLong(cbatchId), "org_id", organizationNewsDO.getId());
                                        if (personnelArrangementDOs != null && personnelArrangementDOs.size() > 0) {
                                            int perSum = personnelArrangementDOs.size();//已有考评员数
                                            for (PersonnelArrangementDO personnelArrangementDO : personnelArrangementDOs) {
                                                if (personnelArrangementDO.getContents().equals("督导员")) {
                                                    iii = false;
                                                    perSum = perSum - 1;
                                                }
                                            }

                                            ppes = perSum;
                                        }

                                        if (examinationBatchDOss != null) {//该认证批次有技能考试时才安排督导员，否则不安排校内督导员
                                            //添加督导员
                                            if (iii) {
                                                PersonnelArrangementDO personnelArrangementDO = new PersonnelArrangementDO();
                                                Map mapa = new HashMap();
                                                mapa.put("type", 3);
                                                mapa.put("orgId", organizationNewsDO.getId());
                                                if (userIdLists != null && userIdLists.size() > 0) {
                                                    mapa.put("userIds", userIdLists);
                                                }
                                                mapa.put("titleNumber", 1);
                                                List<Map<Object, Object>> mapList1 = expertsService.selOrgRandExpList(mapa);
                                                if (mapList1 != null && mapList1.size() > 0) {
                                                    personnelArrangementDO.setOrgId(organizationNewsDO.getId());//考点id
                                                    personnelArrangementDO.setUserId(Long.parseLong(mapList1.get(0).get("userId").toString()));//专家用户id
                                                    personnelArrangementDO.setCbatchId(Long.parseLong(cbatchId));//认证批次id
                                                    personnelArrangementDO.setState(0);//默认正常
                                                    personnelArrangementDO.setContents("督导员");//内容
                                                    personnelArrangementDO.setCreaterId(this.getUserId());//创建人id
                                                    boolean cc = personnelArrangementService.insert(personnelArrangementDO);
                                                    if (cc) {
                                                        userIdLists.add(Long.parseLong(mapList1.get(0).get("userId").toString()));
                                                    }
                                                } else {
                                                    sbOne.append(organizationNewsDO.getName() + ";");
                                                }
                                            }
                                        }

                                        if (endPerNum > ppes) {
                                            endPerNum = endPerNum - ppes;
                                            if (endPerNum > 0) {
                                                //增加考评员
                                                Map mapa = new HashMap();
                                                mapa.put("type", 0);
                                                mapa.put("orgId", organizationNewsDO.getId());
                                                mapa.put("titleNumber", endPerNum);
                                                if (userIdLists != null && userIdLists.size() > 0) {
                                                    mapa.put("userIds", userIdLists);
                                                }
                                                List<Map<Object, Object>> mapList1 = expertsService.selOrgRandExpList(mapa);
                                                if (mapList1 != null && mapList1.size() > 0) {
                                                    if (endPerNum - mapList1.size() >= 0) {
                                                        endPerNum = endPerNum - mapList1.size();
                                                    }
                                                    for (Map map1 : mapList1) {
                                                        PersonnelArrangementDO personnelArrangementDO = new PersonnelArrangementDO();
                                                        personnelArrangementDO.setOrgId(organizationNewsDO.getId());//考点id
                                                        personnelArrangementDO.setUserId(Long.parseLong(map1.get("userId").toString()));//专家用户id
                                                        personnelArrangementDO.setCbatchId(Long.parseLong(cbatchId));//认证批次id
                                                        personnelArrangementDO.setState(0);//默认正常
                                                        personnelArrangementDO.setContents("考评员");//内容
                                                        personnelArrangementDO.setCreaterId(this.getUserId());//创建人id
                                                        boolean cc = personnelArrangementService.insert(personnelArrangementDO);
                                                        if (cc) {
                                                            userIdLists.add(Long.parseLong(map1.get("userId").toString()));
                                                        }
                                                    }
                                                }

                                                if (endPerNum > 0) {
                                                    sbTwo.append(organizationNewsDO.getName() + ";");
                                                }

                                            }
                                        }
                                    }
                                }
                            } else {
                                return Result.fail("该认证批次暂无考点信息！");
                            }
                        } else {
                            return Result.fail("该认证批次暂无考试批次！");
                        }
                    } else {
                        return Result.fail("请分配完所有考生后重试（存在已缴费或待分配考生）！");
                    }
                } else {
                    return Result.fail("请在认证批次报名结束后重试！");
                }
            } else {
                return Result.fail("认证批次信息错误，请检查后重试！");
            }
        } else {
            return Result.fail("请先选择认证批次！");
        }

        if (sbOne.length() > 0 && sbTwo.length() == 0) {
            return Result.fail("考点：" + sbOne + "的督导员不足，请提醒添加后继续！（其他考点已完成安排）");
        } else if (sbTwo.length() > 0 && sbOne.length() == 0) {
            return Result.fail("考点：" + sbTwo + "的考评员不足，请提醒添加后继续！（其他考点已完成安排）");
        } else if (sbTwo.length() > 0 && sbOne.length() > 0) {
            return Result.fail("考点：" + sbOne + "的督导员不足！" + "且考点：" + sbTwo + "的考评员不足，请提醒添加后继续！（其他考点已完成安排）");
        } else {
            return Result.ok("所有考点校内考点人员安排成功");
        }
    }


    @Log("一键安排校外考点人员")
    @GetMapping("/saveExperts")
    @ResponseBody
    public Result<?> saveExperts(String cbatchId) {
        StringBuilder sbOne = new StringBuilder();//校内督导员
        StringBuilder sbTwo = new StringBuilder();//校内考评员
        StringBuilder sbThree = new StringBuilder();//校外督导员
        StringBuilder sbFour = new StringBuilder();//校外考评员
        if (StringUtils.isNotBlank(cbatchId)) {
            //先查询出所有已分配的专家
            List<Long> userIdLists = personnelArrangementService.selUserIdLists(Long.parseLong(cbatchId));
            if (userIdLists == null || userIdLists.size() < 1) {
                userIdLists = new ArrayList<>();
            }

            //先查询认证批次报名时间是否结束，且认证批次是否还存在已缴费和待分配状态的考生，如有，不能安排考点人员；
            CertificationBatchDO certificationBatchDO = certificationBatchService.selectById(Long.parseLong(cbatchId));
            if (certificationBatchDO != null) {
                //现在时间大于认证批次报名结束时间
                Date date = new Date();
                if (date.after(certificationBatchDO.getEndTime())) {
                    //判断是否存在未分配的考生
                    boolean stucc = stuSignUpService.selStuStateIfNull(Long.parseLong(cbatchId));
                    if (stucc) {
                        //根据认证批次id，查询相应的考试批次
                        ExaminationBatchDO examinationBatchDO = examinationBatchService.findOneByKv("cbatch_id", Long.parseLong(cbatchId), "type", 0);
                        if (examinationBatchDO != null) {
                            //循环利用考试批次id查询出所有考点
                            List<Long> orgIds = examinationPointService.selOrgIdLists(examinationBatchDO.getId());
                            if (orgIds != null && orgIds.size() > 0) {
                                for (Long orgID : orgIds) {
                                    OrganizationNewsDO organizationNewsDO = organizationNewsService.selectById(orgID);
                                    //查询到考点的所有已分配的考生数
                                    List<StuSignUpDO> stuSignUpDOS = stuSignUpService.findByKv("cbatch_id", Long.parseLong(cbatchId), "org_id", orgID, "state", 3);
                                    if (stuSignUpDOS != null && stuSignUpDOS.size() > 0) {
                                        int stus = 40;

                                        Map<String, String> mapstus = new HashMap<>();
                                        mapstus.put("name", "考场人数");
                                        mapstus.put("type", "room_number_stu");
                                        String values = dictService.selDicBy(mapstus);
                                        if (org.apache.commons.lang.StringUtils.isNotBlank(values)) {
                                            //判断是否为数字
                                            if (IdCardUtil.isNumeric(values)) {
                                                stus = Integer.parseInt(values);
                                            }
                                        }

                                        int theorys;//理论考场数
                                        if ((stuSignUpDOS.size() % stus) == 0) {
                                            theorys = stuSignUpDOS.size() / stus;
                                        } else {
                                            theorys = (stuSignUpDOS.size() / stus) + 1;
                                        }

                                        int maxDurationNum = 20;
                                        int examinationRoomNum = 6;
                                        mapstus.clear();
                                        mapstus.put("name", "技能考试每组最大时长");
                                        mapstus.put("type", "max_duration");
                                        String maxDuration = dictService.selDicBy(mapstus);
                                        if (org.apache.commons.lang.StringUtils.isNotBlank(maxDuration)) {
                                            //判断是否为数字
                                            if (IdCardUtil.isNumeric(maxDuration)) {
                                                maxDurationNum = Integer.parseInt(maxDuration);
                                            }
                                        }
                                        mapstus.clear();
                                        mapstus.put("name", "技能考场工位数");
                                        mapstus.put("type", "examination_room_number");
                                        String examinationRoomNumber = dictService.selDicBy(mapstus);
                                        if (org.apache.commons.lang.StringUtils.isNotBlank(examinationRoomNumber)) {
                                            //判断是否为数字
                                            if (IdCardUtil.isNumeric(examinationRoomNumber)) {
                                                examinationRoomNum = Integer.parseInt(examinationRoomNumber);
                                            }
                                        }
                                        long minPoor = 180L;//默认为三小时
                                        ExaminationBatchDO examinationBatchDOss = examinationBatchService.findOneByKv("cbatch_id", Long.parseLong(cbatchId), "type", 1);
                                        if (examinationBatchDOss != null) {
                                            minPoor = DateUtil.getDatePoor(examinationBatchDOss.getEndTime(), examinationBatchDOss.getStartTime());//计算设置时长
                                        }

                                        //获取该机构的技能考场数量
                                        Map mapAllNum = new HashMap();
                                        mapAllNum.put("profileId", certificationBatchDO.getProfileId());
                                        mapAllNum.put("orgId", orgID);
                                        int roomAllNum = examinationRoomService.selTypeCount(mapAllNum);

                                        long stationNum;//技能考试所需考评员数
                                        if (minPoor == 0) {
                                            stationNum = 0;
                                        } else {
                                            long earooms;//技能考场数
                                            if (((stuSignUpDOS.size() * maxDurationNum) % (minPoor * examinationRoomNum)) == 0) {
                                                earooms = (stuSignUpDOS.size() * maxDurationNum) / (minPoor * examinationRoomNum);
                                            } else {
                                                earooms = (stuSignUpDOS.size() * maxDurationNum) / (minPoor * examinationRoomNum) + 1;
                                            }

                                            if(earooms > roomAllNum){
                                                if ((examinationRoomNum % 3) == 0) {
                                                    stationNum = (examinationRoomNum / 3) * roomAllNum;
                                                } else {
                                                    stationNum = ((examinationRoomNum / 3) + 1) * roomAllNum;
                                                }
                                            }else{
                                                if ((examinationRoomNum % 3) == 0) {
                                                    stationNum = (examinationRoomNum / 3) * earooms;
                                                } else {
                                                    stationNum = ((examinationRoomNum / 3) + 1) * earooms;
                                                }
                                            }
                                        }

                                        long endPerNum;//需要安排的考评员数量
                                        if (stationNum >= theorys) {
                                            endPerNum = stationNum;
                                        } else {
                                            endPerNum = theorys;
                                        }

                                        int ppes = 0;//已有考评员数
                                        //判断并增加督导员
                                        int iii = 0;
                                        List<PersonnelArrangementDO> personnelArrangementDOs = personnelArrangementService.findByKv("cbatch_id", Long.parseLong(cbatchId), "org_id", organizationNewsDO.getId());
                                        if (personnelArrangementDOs != null && personnelArrangementDOs.size() > 0) {
                                            int perSum = personnelArrangementDOs.size();//已有考评员数
                                            for (PersonnelArrangementDO personnelArrangementDO : personnelArrangementDOs) {
                                                if (personnelArrangementDO.getContents().equals("督导员")) {
                                                    iii++;
                                                    perSum = perSum - 1;
                                                }
                                            }

                                            ppes = perSum;
                                        }

                                        if (examinationBatchDOss != null) {//该认证批次有技能考试时才安排督导员，否则不安排校内督导员
                                            if (iii == 0) {
                                                sbOne.append(organizationNewsDO.getName() + ";");
                                            }
                                        }

                                        long edss = endPerNum;
                                        if (edss > ppes) {
                                            edss = edss - ppes;
                                            if (edss > 0) {
                                                sbTwo.append(organizationNewsDO.getName() + ";");
                                            }
                                        }

                                        //如果校内考点人员未安排完毕，则安排校外考评员
                                        if(sbOne.length() == 0 && sbTwo.length() == 0){
                                            //判断并添加校外考点人员信息
                                            if (iii == 1) {//添加督导员
                                                PersonnelArrangementDO personnelArrangementDO = new PersonnelArrangementDO();
                                                Map mapa = new HashMap();
                                                mapa.put("type", 3);
                                                mapa.put("province", organizationNewsDO.getProvince());
                                                mapa.put("orgId", organizationNewsDO.getId());
                                                if (userIdLists != null && userIdLists.size() > 0) {
                                                    mapa.put("userIds", userIdLists);
                                                }
                                                mapa.put("titleNumber", 1);
                                                List<Map<Object, Object>> mapList1 = expertsService.selRandExpList(mapa);
                                                if (mapList1 != null && mapList1.size() > 0) {
                                                    personnelArrangementDO.setOrgId(organizationNewsDO.getId());//考点id
                                                    personnelArrangementDO.setUserId(Long.parseLong(mapList1.get(0).get("userId").toString()));//专家用户id
                                                    personnelArrangementDO.setCbatchId(Long.parseLong(cbatchId));//认证批次id
                                                    personnelArrangementDO.setState(0);//默认正常
                                                    personnelArrangementDO.setContents("督导员");//内容
                                                    personnelArrangementDO.setCreaterId(this.getUserId());//创建人id
                                                    boolean cc = personnelArrangementService.insert(personnelArrangementDO);
                                                    if (cc) {
                                                        userIdLists.add(Long.parseLong(mapList1.get(0).get("userId").toString()));
                                                    }
                                                } else {
                                                    mapa.clear();
                                                    mapa.put("type", 3);
                                                    mapa.put("province", null);
                                                    mapa.put("orgId", organizationNewsDO.getId());
                                                    if (userIdLists != null && userIdLists.size() > 0) {
                                                        mapa.put("userIds", userIdLists);
                                                    }
                                                    mapa.put("titleNumber", 1);
                                                    List<Map<Object, Object>> mapList2 = expertsService.selRandExpList(mapa);
                                                    if (mapList2 != null && mapList2.size() > 0) {
                                                        personnelArrangementDO.setOrgId(organizationNewsDO.getId());//考点id
                                                        personnelArrangementDO.setUserId(Long.parseLong(mapList2.get(0).get("userId").toString()));//专家用户id
                                                        personnelArrangementDO.setCbatchId(Long.parseLong(cbatchId));//认证批次id
                                                        personnelArrangementDO.setState(0);//默认正常
                                                        personnelArrangementDO.setContents("督导员");//内容
                                                        personnelArrangementDO.setCreaterId(this.getUserId());//创建人id
                                                        boolean cc = personnelArrangementService.insert(personnelArrangementDO);
                                                        if (cc) {
                                                            userIdLists.add(Long.parseLong(mapList2.get(0).get("userId").toString()));
                                                        }
                                                    } else {
                                                        sbThree.append(organizationNewsDO.getName() + ";");
                                                    }
                                                }
                                            }

                                            long endssd = endPerNum * 2;
                                            if (endssd > ppes) {
                                                endssd = endssd - ppes;
                                                if (endssd > 0) {
                                                    //增加考评员
                                                    Map mapa = new HashMap();
                                                    mapa.put("type", 0);
                                                    mapa.put("province", organizationNewsDO.getProvince());
                                                    mapa.put("orgId", organizationNewsDO.getId());
                                                    mapa.put("titleNumber", endssd);
                                                    if (userIdLists != null && userIdLists.size() > 0) {
                                                        mapa.put("userIds", userIdLists);
                                                    }
                                                    List<Map<Object, Object>> mapList1 = expertsService.selRandExpList(mapa);
                                                    if (mapList1 != null && mapList1.size() > 0) {
                                                        if (endssd - mapList1.size() >= 0) {
                                                            endssd = endssd - mapList1.size();
                                                        }
                                                        for (Map map1 : mapList1) {
                                                            PersonnelArrangementDO personnelArrangementDO = new PersonnelArrangementDO();
                                                            personnelArrangementDO.setOrgId(organizationNewsDO.getId());//考点id
                                                            personnelArrangementDO.setUserId(Long.parseLong(map1.get("userId").toString()));//专家用户id
                                                            personnelArrangementDO.setCbatchId(Long.parseLong(cbatchId));//认证批次id
                                                            personnelArrangementDO.setState(0);//默认正常
                                                            personnelArrangementDO.setContents("考评员");//内容
                                                            personnelArrangementDO.setCreaterId(this.getUserId());//创建人id
                                                            boolean cc = personnelArrangementService.insert(personnelArrangementDO);
                                                            if (cc) {
                                                                userIdLists.add(Long.parseLong(map1.get("userId").toString()));
                                                            }
                                                        }
                                                    }

                                                    //安排省内考评员后，如还是不够，则默认分配省外考评员
                                                    if (endssd > 0) {
                                                        mapa.clear();
                                                        mapa.put("type", 0);
                                                        mapa.put("province", null);
                                                        mapa.put("orgId", organizationNewsDO.getId());
                                                        if (userIdLists != null && userIdLists.size() > 0) {
                                                            mapa.put("userIds", userIdLists);
                                                        }
                                                        mapa.put("titleNumber", endssd);
                                                        List<Map<Object, Object>> mapList2 = expertsService.selRandExpList(mapa);
                                                        if (mapList2 != null && mapList2.size() > 0) {
                                                            if (endssd - mapList2.size() >= 0) {
                                                                endssd = endssd - mapList2.size();
                                                            }
                                                            for (Map map1 : mapList2) {
                                                                PersonnelArrangementDO personnelArrangementDO = new PersonnelArrangementDO();
                                                                personnelArrangementDO.setOrgId(organizationNewsDO.getId());//考点id
                                                                personnelArrangementDO.setUserId(Long.parseLong(map1.get("userId").toString()));//专家用户id
                                                                personnelArrangementDO.setCbatchId(Long.parseLong(cbatchId));//认证批次id
                                                                personnelArrangementDO.setState(0);//默认正常
                                                                personnelArrangementDO.setContents("考评员");//内容
                                                                personnelArrangementDO.setCreaterId(this.getUserId());//创建人id
                                                                boolean cc = personnelArrangementService.insert(personnelArrangementDO);
                                                                if (cc) {
                                                                    userIdLists.add(Long.parseLong(map1.get("userId").toString()));
                                                                }
                                                            }
                                                        }
                                                    }

                                                    if (endssd > 0) {
                                                        sbFour.append(organizationNewsDO.getName() + ";");
                                                    }
                                                }
                                            }

                                        }
                                    }
                                }

                            } else {
                                return Result.fail("该认证批次暂无考点信息！");
                            }
                        } else {
                            return Result.fail("该认证批次暂无考试批次！");
                        }
                    } else {
                        return Result.fail("请分配完所有考生后重试（存在已缴费或待分配考生）！");
                    }
                } else {
                    return Result.fail("请在认证批次报名结束后重试！");
                }
            } else {
                return Result.fail("认证批次信息错误，请检查后重试！");
            }
        } else {
            return Result.fail("请先选择认证批次");
        }


        if (sbOne.length() > 0 && sbTwo.length() == 0) {
            return Result.fail("考点：" + sbOne + "的校内督导员未安排完成，请安排后重试！");
        } else if (sbTwo.length() > 0 && sbOne.length() == 0) {
            return Result.fail("考点：" + sbTwo + "的校内考评员未安排完成，请安排后重试！");
        } else if (sbTwo.length() > 0 && sbOne.length() > 0) {
            return Result.fail("考点：" + sbOne + "的校内督导员" + "且考点：" + sbTwo + "的校内考评员未安排完成，请安排后重试！");
        } else {
            if (sbThree.length() > 0 && sbFour.length() == 0) {
                return Result.fail("校外督导员不足，考点：" + sbThree + "暂未安排完成，请添加后继续！（其他考点已完成安排）");
            } else if (sbFour.length() > 0 && sbThree.length() == 0) {
                return Result.fail("校外考评员不足，考点：" + sbFour + "暂未安排完成，请添加后继续！（其他考点已完成安排）");
            } else if (sbThree.length() > 0 && sbFour.length() > 0) {
                return Result.fail("校外督导员不足，考点：" + sbThree + "暂未安排完成！" + "且校外考评员不足，考点：" + sbFour + "暂未安排完成，请添加后继续！（其他考点已完成安排）");
            } else {
                return Result.ok("所有校外考点人员安排成功");
            }
        }
    }
}
